package com.huangfuyi.home.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.huangfuyi.home.dao.BaiduDiskTokenDao;
import com.huangfuyi.home.entity.BaiduDiskTokenEntity;
import com.huangfuyi.home.service.BaiduDiskTokenService;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class BaiduDiskTokenServiceImpl implements BaiduDiskTokenService {

    @Autowired
    private BaiduDiskTokenDao baiduDiskTokenDao;

    private final String baiduDiskTokenId = "00000000000000000000000000000000";


    @Override
    public BaiduDiskTokenEntity queryById() {
        return baiduDiskTokenDao.queryById(baiduDiskTokenId);
    }

    @Override
    public void update() throws Exception{
        BaiduDiskTokenEntity tokenInfoOld = baiduDiskTokenDao.queryById(baiduDiskTokenId);
        String refrashToken = tokenInfoOld.getRefreshToken();
        String appKey = tokenInfoOld.getAppKey();
        String secretKey = tokenInfoOld.getSecretKey();

        CloseableHttpClient client = HttpClients.createDefault();

        String codeGetUrl = "https://openapi.baidu.com/oauth/2.0/token?" +
                "grant_type=refresh_token&" +
                "refresh_token="+refrashToken+"&" +
                "client_id="+appKey+"&" +
                "client_secret=" + secretKey;
        HttpGet get = new HttpGet(codeGetUrl);
        CloseableHttpResponse response = client.execute(get);
        HttpEntity entity = response.getEntity();
        String newTokenInfoStr = EntityUtils.toString(entity);
        JSONObject newTokenInfoJson = JSON.parseObject(newTokenInfoStr);

        BaiduDiskTokenEntity updateData = new BaiduDiskTokenEntity();
        updateData.setId(tokenInfoOld.getId());
        updateData.setExpiresIn(newTokenInfoJson.getLong("expires_in"));
        updateData.setAccessToken(newTokenInfoJson.getString("access_token"));
        updateData.setRefreshToken(newTokenInfoJson.getString("refresh_token"));
        updateData.setUpdateTime(System.currentTimeMillis());

        baiduDiskTokenDao.update(updateData);
    }
}
